package com.jasperframework.boot.common.utils;

/**
  * <p> 文件加密  </p>
  *
  * @site https://miliqkdoc.motopa.cn/
  * @author daizhao
  * @date 2022/12/12 12:12
  */

import java.io.*;

public class FileEncAndDec {

    private static final int numOfEncAndDec = 0x99; //加密解密秘钥
    private static int dataOfFile = 0; //文件字节内容

    public static void main(String[] args) {

        File srcFile = new File("d:/timg.gif"); //初始文件
        File encFile = new File("d:/encFile.tif"); //加密文件
        File decFile = new File("d:/decFile.gif"); //解密文件

        try {
            EncFile(srcFile, encFile); //加密操作
            DecFile(encFile, decFile); //解密操作
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  @Author daizhao
     *  @Date 2018-4-2 11:48
     *  @Params [srcFile, encFile]
     *  @Return void
     *  @Info   des加密
     */
    private static void EncFile(File srcFile, File encFile) throws Exception {

        if (!srcFile.exists()) {
            System.out.println("source file not exixt");
            return;
        }

        if (!encFile.exists()) {
            System.out.println("encrypt file created");
            encFile.createNewFile();
        }
        InputStream fis = new FileInputStream(srcFile);
        OutputStream fos = new FileOutputStream(encFile);

        while ((dataOfFile = fis.read()) > -1) {
            fos.write(dataOfFile ^ numOfEncAndDec);
        }

        fis.close();
        fos.flush();
        fos.close();
    }

    /**
     *  @Author daizhao
     *  @Date 2018-4-2 11:48
     *  @Params [encFile, decFile]
     *  @Return void
     *  @Info   des解密
     */
    private static void DecFile(File encFile, File decFile) throws Exception {

        if (!encFile.exists()) {
            System.out.println("encrypt file not exixt");
            return;
        }

        if (!decFile.exists()) {
            System.out.println("decrypt file created");
            decFile.createNewFile();
        }

        InputStream fis = new FileInputStream(encFile);
        OutputStream fos = new FileOutputStream(decFile);

        while ((dataOfFile = fis.read()) > -1) {
            fos.write(dataOfFile ^ numOfEncAndDec);
        }

        fis.close();
        fos.flush();
        fos.close();
    }


}


